<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \App\Post;
use \App\Comment;
use \App\Like;

class PostController extends Controller
{
    // 列表
    public function index()
    {
        $posts = Post::orderBy('created_at','desc')->withCount(['comments','likes'])->paginate(6);
        return view("post.index",compact('posts'));
    }
    
    // 文章详情
    public function show(Post $post)
    {
        // 模型预加载
        $post->load('comments');
        return view("post.show",compact('post'));
    }
    
    // 创建页面
    public function create()
    {
        return view("post.create");
    }
    
    // 创建逻辑
    public function store()
    {
        // 验证
        $this->validate(request(),[
            'title' => 'required|string|max:100|min:5',
            'content' => 'required|string|min:10'
        ]);

        // 逻辑
        $user_id = \Auth::id();
        $params = array_merge(request(['title','content']),compact('user_id'));
        $post = Post::create($params);
        return redirect('/posts');
    }

    // 编辑页面
    public function edit(Post $post)
    {
        // dd($post);
        return view("post/edit",compact('post'));
    }

    // 编辑逻辑
    public function update(Post $post)
    {
        $this->validate(request(),[
            'title' => 'required|string|max:100|min:5',
            'content' => 'required|string|min:10'
        ]);

        $this->authorize('update',$post);
        // 逻辑
        $post->title = request('title');
        $post->content = request('content');
        $post->save();

        // 渲染
        return redirect("/posts/{$post->id}");

    }

    // 删除文章
    public function delete(Post $post)
    {
        // 用户权限验证
        $this->authorize('delete',$post);
        $post->delete();
        return redirect('/posts');
    }

    // 上传图片
    public function imageUpload(Request $request)
    {
        $path = $request->file('yourFileName')->storePublicly(md5(time()));
        $data = ['errno' => 0,'data' => asset('storage/'.$path)];
        return json_encode($data);
        // dd(request()->all());
    }

    // 提交评论
    public function comment(Post $post)
    {
        // 验证
        $this->validate(request(),[
            'content' => 'required|min:3',
        ]);

        // 逻辑
        $comment = new Comment();
        $comment->user_id = \Auth::id();
        $comment->content = request('content');
        $post->comments()->save($comment);
        // 渲染
        return back();
    }

    // 赞
    public function like(Post $post)
    {
        $params = [
            'user_id' => \Auth::id(),
            'post_id' =>$post->id
        ];

        Like::firstOrCreate($params);

        return back();
    }

    public function unlike(Post $post)
    {
        $post->like(\Auth::id())->delete();
        return back();
    }
}
